package com.speedydial;

import org.apache.log4j.Level;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.database.SQLException;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

import com.speedydial.persistence.MessageDbAdapter;

import de.mindpipe.android.logging.log4j.LogConfigurator;

/**
 * Por ahora solo practicando el Activity
 * 
 * @author mario
 * 
 */
public class Main extends ListActivity {

	private static final int ACTIVITY_CREATE = 0;
	private static final int ACTIVITY_EDIT = 1;
	private static final int ACTIVITY_CONFIG = 2;

	private static final String TAG = "MainActivity";

	private static final Logger LOG = LoggerFactory.getLogger(TAG);
	private MessageDbAdapter mDbHelper;
	private Cursor messagesCursor;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.message_list);

		// configuring the log
		configureLog();

		// setting the database routines
		mDbHelper = new MessageDbAdapter(this);

		try {
			mDbHelper.open();
		} catch (SQLException ex) {
			LOG.error("Error abriendo: " + ex.getMessage(), ex);
		}

		// anadiendo otros widgets
		Button jumpToBtn = (Button) findViewById(R.id.jumpBtn);
		jumpToBtn.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// because we are inside an inner class, we need to
				// get an instance of the outer class
				Intent flip = new Intent(Main.this, EditSMSForm.class);
				startActivityForResult(flip, ACTIVITY_CREATE);
			}
		});

		// por ahora comentamos la creacion de la base de datos
		fillData();
		// mDbHelper.close();
	}

	private void configureLog() {
		final LogConfigurator logConfigurator = new LogConfigurator();

		logConfigurator.setFileName("/data/data/com.speedydial/logs"
				+ "/speedy.log");
		logConfigurator.setRootLevel(Level.INFO);
		// Set log level of a specific logger
		logConfigurator.setLevel("org.apache", Level.ERROR);
		logConfigurator.setLevel("com.speedydial.persistence", Level.ERROR);
		logConfigurator.configure();
	}

	@Override
	protected void onResume() {
		super.onResume();
		try {
			mDbHelper = mDbHelper.openReadable();
		} catch (SQLException ex) {
			LOG.error("Error abriendo bbdd",ex);
		}
	}

	@Override
	protected void onStop() {
		super.onStop();
	}

	private void fillData() {

		LOG.debug(TAG, "filling data");

		// Get all of the notes from the database and create the item list
		// Cursor c = mDbHelper.fetchAllNotes();
		messagesCursor = mDbHelper.fetchAllNotes();
		// startManagingCursor(c);
		startManagingCursor(messagesCursor);

		String[] from = new String[] { MessageDbAdapter.KEY_TITLE };
		int[] to = new int[] { R.id.message };

		// Now create an array adapter and set it to display using our row
		SimpleCursorAdapter notes = new SimpleCursorAdapter(this,
				R.layout.list_item, messagesCursor, from, to);

		// TODO: descomentar al momento de cambiar a ListActivity
		setListAdapter(notes);
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		Cursor c = mDbHelper.fetchAllNotes();
		c.moveToPosition(position);
		Intent i = new Intent(this, EditSMSForm.class);
		i.putExtra(MessageDbAdapter.KEY_ROWID, id);
		i.putExtra(MessageDbAdapter.KEY_TITLE, c.getString(c
				.getColumnIndexOrThrow(MessageDbAdapter.KEY_TITLE)));
		i.putExtra(MessageDbAdapter.KEY_EMAIL,
				c.getString(c.getColumnIndexOrThrow(MessageDbAdapter.KEY_EMAIL)));
		startActivityForResult(i, ACTIVITY_EDIT);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode,
			Intent intent) {
		super.onActivityResult(requestCode, resultCode, intent);
		fillData();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.speedy_menu, menu);

		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		switch (item.getItemId()) {
		case R.id.add_menu:
			// do the magic
			Intent flip = new Intent(this, ConfigMovementActivity.class);
			startActivityForResult(flip, ACTIVITY_CONFIG);
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}

	}

}
